import { ParameterizedContext, Next } from 'koa';
import { Connection } from 'typeorm';
import { typeorm } from '../bin/db';

export default async function(ctx: ParameterizedContext, next: Next) {
  try {
    if (!ctx.db) {
      const connection: Connection = await typeorm();
      ctx.db = { connection };
    }
    await next();
  } catch (error) {
    ctx.body = {
      message: `数据库连接错误`,
      code: 500,
      error,
    };
  }
}
